import 'package:flutter/material.dart';

/// 登录页面
/// 包含手机号验证码登录和密码登录两种方式
class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // =============== 控制器定义 ===============
  /// 手机号输入控制器
  final TextEditingController _phoneController = TextEditingController();
  
  /// 验证码/密码输入控制器
  final TextEditingController _codeOrPasswordController = TextEditingController();

  // =============== 状态变量 ===============
  /// 是否为验证码登录模式
  /// true: 验证码登录
  /// false: 密码登录
  bool _isVerifyCodeLogin = true;

  /// 当前选中的国家代码
  String _selectedCountryCode = '+86';

  /// 密码是否可见
  bool _isPasswordVisible = false;

  /// 国家/地区代码列表
  /// 每个项目包含:
  /// - code: 国际电话区号
  /// - name: 国家/地区名称
  final List<Map<String, String>> _countryCodes = [
    {'code': '+86', 'name': '中国大陆'},
    {'code': '+852', 'name': '中国香港'},
    {'code': '+853', 'name': '中国澳门'},
    {'code': '+886', 'name': '中国台湾'},
    {'code': '+1', 'name': '美国'},
    {'code': '+81', 'name': '日本'},
    {'code': '+82', 'name': '韩国'},
    {'code': '+44', 'name': '英国'},
    {'code': '+65', 'name': '新加坡'},
    {'code': '+60', 'name': '马来西亚'},
  ];

  // =============== UI构建方法 ===============
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: _buildMainContent(),
      ),
    );
  }

  /// 构建主体内容
  Widget _buildMainContent() {
    return CustomScrollView(
      slivers: [
        SliverFillRemaining(
          hasScrollBody: false,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 24.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                _buildLogoSection(),
                _buildLoginTypeSwitch(),
                const SizedBox(height: 32),
                _buildPhoneInput(),
                const SizedBox(height: 16),
                _buildVerificationCodeInput(),
                const SizedBox(height: 16),
                _buildAgreementSection(),
                const SizedBox(height: 24),
                _buildLoginButton(),
                const SizedBox(height: 16),
                _buildDivider(),
                const SizedBox(height: 16),
                _buildWeChatLoginButton(),
                Expanded(child: SizedBox()),
                _buildContactUs(),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建Logo区域
  Widget _buildLogoSection() {
    return Container(
      height: 120,
      margin: EdgeInsets.only(top: 40, bottom: 40),
      child: Center(
        child: Container(
          width: 200,
          height: 80,
          decoration: BoxDecoration(
            color: Colors.grey[200],
            borderRadius: BorderRadius.circular(8),
          ),
          child: Icon(
            Icons.image_outlined,
            size: 40,
            color: Colors.grey[400],
          ),
        ),
      ),
    );
  }

  /// 构建登录方式切换按钮
  Widget _buildLoginTypeSwitch() {
    return Row(
      children: [
        _buildLoginTypeButton('验证码登录/注册', true),
        const SizedBox(width: 16),
        _buildLoginTypeButton('密码登录', false),
      ],
    );
  }

  /// 构建登录类型按钮
  Widget _buildLoginTypeButton(String text, bool isVerifyCode) {
    return TextButton(
      onPressed: () => _handleLoginTypeChange(isVerifyCode),
      child: Text(
        text,
        style: TextStyle(
          color: _isVerifyCodeLogin == isVerifyCode
              ? Colors.blue
              : Colors.grey,
        ),
      ),
    );
  }

  /// 构建手机号输入区域
  Widget _buildPhoneInput() {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey[300]!),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          _buildCountryCodeSelector(),
          Expanded(
            child: TextField(
              controller: _phoneController,
              keyboardType: TextInputType.phone,
              decoration: InputDecoration(
                hintText: '手机号',
                border: InputBorder.none,
                contentPadding: EdgeInsets.symmetric(horizontal: 12),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建国家代码选择器
  Widget _buildCountryCodeSelector() {
    return InkWell(
      onTap: _showCountryCodePicker,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 12),
        child: Row(
          children: [
            Text(
              _selectedCountryCode,
              style: TextStyle(fontSize: 16),
            ),
            SizedBox(width: 4),
            Icon(
              Icons.arrow_drop_down,
              color: Colors.grey,
            ),
            Container(
              height: 20,
              width: 1,
              margin: EdgeInsets.symmetric(horizontal: 8),
              color: Colors.grey[300],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建验证码/密码输入区域
  Widget _buildVerificationCodeInput() {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey[300]!),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Expanded(
            child: TextField(
              controller: _codeOrPasswordController,
              obscureText: !_isVerifyCodeLogin && !_isPasswordVisible,
              decoration: InputDecoration(
                hintText: _isVerifyCodeLogin ? '验证码' : '密码',
                border: InputBorder.none,
                contentPadding: EdgeInsets.symmetric(horizontal: 12),
              ),
            ),
          ),
          // 根据登录方式显示不同的按钮
          if (_isVerifyCodeLogin)
            TextButton(
              onPressed: _handleSendVerificationCode,
              child: Text('发送验证码'),
            )
          else
            IconButton(
              icon: Icon(
                _isPasswordVisible ? Icons.visibility_off : Icons.visibility,
                color: Colors.grey,
              ),
              onPressed: () {
                setState(() {
                  _isPasswordVisible = !_isPasswordVisible;
                });
              },
            ),
        ],
      ),
    );
  }

  /// 构建用户协议区域
  Widget _buildAgreementSection() {
    return Wrap(
      alignment: WrapAlignment.center,
      children: [
        Text('登录/注册即代表同意'),
        _buildAgreementButton('用户协议'),
        Text('和'),
        _buildAgreementButton('隐私政策'),
      ],
    );
  }

  /// 构建协议按钮
  Widget _buildAgreementButton(String title) {
    return TextButton(
      onPressed: () => _showAgreement(title),
      style: TextButton.styleFrom(
        padding: EdgeInsets.zero,
        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
        minimumSize: Size(0, 0),
      ),
      child: Text('《$title》'),
    );
  }

  /// 构建登录按钮
  Widget _buildLoginButton() {
    return ElevatedButton(
      onPressed: _handleLogin,
      style: ElevatedButton.styleFrom(
        padding: EdgeInsets.symmetric(vertical: 12),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
      ),
      child: Text('登录'),
    );
  }

  /// 构建分割线
  Widget _buildDivider() {
    return Row(
      children: [
        Expanded(child: Divider()),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: Text('或'),
        ),
        Expanded(child: Divider()),
      ],
    );
  }

  /// 构建微信登录按钮
  Widget _buildWeChatLoginButton() {
    return OutlinedButton(
      onPressed: _handleWeChatLogin,
      style: OutlinedButton.styleFrom(
        padding: EdgeInsets.symmetric(vertical: 12),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.chat_bubble_outline),
          SizedBox(width: 8),
          Text('使用微信登录'),
        ],
      ),
    );
  }

  /// 构建联系我们按钮
  Widget _buildContactUs() {
    return Center(
      child: Padding(
        padding: EdgeInsets.only(
          bottom: MediaQuery.of(context).viewInsets.bottom > 0 
              ? 16 
              : MediaQuery.of(context).padding.bottom + 16,
        ),
        child: TextButton(
          onPressed: _handleContactUs,
          child: Text('联系我们'),
        ),
      ),
    );
  }

  // =============== 事件处理方法 ===============
  
  /// 处理登录类型切换
  void _handleLoginTypeChange(bool isVerifyCode) {
    setState(() {
      _isVerifyCodeLogin = isVerifyCode;
      // 切换登录方式时清空输入
      _codeOrPasswordController.clear();
    });
  }

  /// 显示国家代码选择器
  void _showCountryCodePicker() {
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) => _buildCountryCodePickerContent(),
    );
  }

  /// 构建国家代码选择器内容
  Widget _buildCountryCodePickerContent() {
    return SizedBox(
      height: MediaQuery.of(context).size.height * 0.6,
      child: Column(
        children: [
          _buildCountryCodePickerHeader(),
          Expanded(
            child: ListView.builder(
              itemCount: _countryCodes.length,
              itemBuilder: _buildCountryCodeItem,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建国家代码选择器头部
  Widget _buildCountryCodePickerHeader() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 16),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Colors.grey[200]!),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            '选择国家和地区',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建国家代码列表项
  Widget _buildCountryCodeItem(BuildContext context, int index) {
    final country = _countryCodes[index];
    return ListTile(
      onTap: () => _handleCountryCodeSelect(country['code']!),
      title: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(country['name']!),
          Text(
            country['code']!,
            style: TextStyle(color: Colors.grey),
          ),
        ],
      ),
      selected: _selectedCountryCode == country['code'],
    );
  }

  /// 处理国家代码选择
  void _handleCountryCodeSelect(String code) {
    setState(() {
      _selectedCountryCode = code;
    });
    Navigator.pop(context);
  }

  /// 处理发送验证码
  void _handleSendVerificationCode() {
    final String phone = _phoneController.text;
    if (phone.isEmpty) {
      _showToast('请输入手机号');
      return;
    }
    print('发送验证码到: $phone');
    // TODO: 实现验证码发送逻辑
  }

  /// 处理登录按钮点击
  void _handleLogin() {
    final String phone = _phoneController.text;
    final String codeOrPassword = _codeOrPasswordController.text;

    if (phone.isEmpty) {
      _showToast('请输入手机号');
      return;
    }

    if (codeOrPassword.isEmpty) {
      _showToast(_isVerifyCodeLogin ? '请输入验证码' : '请输入密码');
      return;
    }

    if (_isVerifyCodeLogin) {
      _handleVerifyCodeLogin(phone, codeOrPassword);
    } else {
      _handlePasswordLogin(phone, codeOrPassword);
    }
  }

  /// 处理验证码登录
  void _handleVerifyCodeLogin(String phone, String code) {
    print('验证码登录: 手机号=$phone, 验证码=$code');
    // TODO: 实现验证码登录逻辑
  }

  /// 处理密码登录
  void _handlePasswordLogin(String phone, String password) {
    print('密码登录: 手机号=$phone, 密码=$password');
    // TODO: 实现密码登录逻辑
  }

  /// 处理微信登录
  void _handleWeChatLogin() {
    print('微信登录');
    Navigator.pushNamed(context, '/home');
    // TODO: 实现微信登录逻辑
  }

  /// 显示协议内容
  void _showAgreement(String type) {
    if (type == '用户协议') {
      Navigator.pushNamed(context, '/agreement', arguments: type);
    } else if (type == '隐私政策') {
      Navigator.pushNamed(context, '/privacy_policy', arguments: type);
    }
  }

  /// 处理联系我们点击
  void _handleContactUs() {
    print('联系我们');
    // TODO: 实现联系我们逻辑
  }

  /// 显示提示信息
  void _showToast(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }

  // =============== 生命周期方法 ===============
  @override
  void dispose() {
    // 释放控制器资源
    _phoneController.dispose();
    _codeOrPasswordController.dispose();
    super.dispose();
  }
}
